import xlrd
import numpy as np
import scipy.io as sio
from matplotlib import pyplot as plt
import os
import time
import Initial_Settings
# import MSJJ_Fit
import sys
sys.path.append(r'X:\Work\Rb87Python')
sys.path.append(r'D:\vc\Rb87Python')
import socket

os.system('chcp 65001')
Host_Name = socket.gethostname()
Computer_Name = r'\\calcenter2'+'\\'
if Host_Name == 'VictorChengPC':
    Excel_Name = 'X:\\Work\\mail.ustc.edu.cn\\Rb87BEC - Files\\'
elif Host_Name == 'calcenter2':
    Excel_Name = 'D:\\vc\\mail.ustc.edu.cn\\Rb87BEC - Files\\'
import basic_function.Rb87BEC_Basic_Functions as bf
# Index = 0.05

#%%
time_start=time.time()

#%% Switches
FitBEC_Switch = 0
FitDraw_Switch = 0
OriImage_Switch = 1
Data_Total = []
#%% Modes
File_Mode = 1
Atom_Mode = 0

#%% Initial settings

#Mat_Data = [128 -1, 137 -1, 146 -1]
Mat_Data = np.linspace(49, 65, 17).astype(int)
Part_Num = 1; Num_of_Repeat = 6; Total_Time = 51
Data_Exl = xlrd.open_workbook\
(Excel_Name+r'Rb87files\phase_stability\ps.xlsx')
Table = Data_Exl.sheets()[0]
# Matrix_Shift = [0, 0]
clims = [-0.1, 0.5]
# Wait_Sec = 1
Photo_Name_Tag='4550test_'
Photo_Total = ''
if File_Mode == 0:
    PhotoName_Pre = 'ascOD'+Photo_Name_Tag
    PhotoName_End = '.asc'
    
elif File_Mode == 1:
    PhotoName_Pre = Photo_Name_Tag
    PhotoName_End = 'od.mat'

#%% Calculate all photos
for Row_Num in range(len(Mat_Data)):
    Data_ThisRow = []
    Exl_RowNum = Mat_Data[Row_Num]
    Input_Matrix = Table.row_values(Exl_RowNum)
    Parameters = {}

    # Set parameters
    YearMonthDay = str(int(Input_Matrix[0]))
    Parameters['YearMonthDay'] = YearMonthDay
    Ini_Photo = int(Input_Matrix[1])
    Parameters['Ini_Photo'] = Ini_Photo
    Fin_Photo = int(Input_Matrix[2])
    Parameters['Fin_Photo'] = Fin_Photo
    Repeat = int(Input_Matrix[3])
    Parameters['Repeat'] = Repeat
    t_Ini = int(Input_Matrix[4])
    Parameters['t_Ini'] = t_Ini
    t_End = int(Input_Matrix[5])
    Parameters['t_End'] = t_End
    Time_Step = int(Input_Matrix[6])
    Parameters['Time_Step'] = Time_Step
    Resonance = Input_Matrix[7]
    Parameters['Resonance'] = Resonance
    omega = Input_Matrix[8]
    Parameters['omega'] = omega
    Measure_Mode = int(Input_Matrix[9])
    Parameters['Measure_Mode'] = Measure_Mode
    V0 = Input_Matrix[10]
    Parameters['V0'] = V0
    M0 = Input_Matrix[11]
    Parameters['M0'] = M0
    Detuning = Input_Matrix[12]
    Parameters['Detuning'] = Detuning
    Parameters_str = str(Parameters)
    Parameters_str = Parameters_str.replace('{', '')
    Parameters_str = Parameters_str.replace('}', '')
    Parameters_str = Parameters_str.replace(' ', '')
    Parameters_str = Parameters_str.replace(':', '=')
    Photo = str(Ini_Photo)+'To'+str(Fin_Photo)
    Photo_Total += Photo+';'
    if (t_End-t_Ini)/Time_Step+1 != Fin_Photo-Ini_Photo+1:
        input('Wrong input. Go check. Row index: %d\n'%(Exl_RowNum+1))


    #Data matrices
    if Row_Num == 0:
        Ratio_Mat = np.zeros((len(Mat_Data), Fin_Photo-Ini_Photo+1))
        smalls = np.zeros((len(Mat_Data), Fin_Photo-Ini_Photo+1))
        Time = np.linspace(t_Ini, t_End, (t_End-t_Ini)/Time_Step+1)

    #Addresses
    if File_Mode == 0:
        Folder_Name = r'\\CAMERA-PC\ShareFolder'+'\\'+\
        YearMonthDay+r'morning\4552'+'\\'
    elif File_Mode == 1:
        Folder_Name = Computer_Name+'oriData'+'\\'+YearMonthDay+'\\'
    Save_Address = Computer_Name+r'Rb87figures\phase_stability'+'\\'+\
    YearMonthDay+'\\'+Photo+'\\'
    os.system('mkdir '+Save_Address)
    SaveFigure_Address = Computer_Name+r'Rb87figures\phase_stability\figures'+'\\'+\
    YearMonthDay+'\\'+Photo+'\\'
    os.system('mkdir '+SaveFigure_Address)
    SaveFolder_Name = Computer_Name+r'dataProcessResult\oriData'+'\\'+\
    YearMonthDay+'\\'
    os.system('mkdir '+SaveFolder_Name)
    Save_Name = YearMonthDay+Parameters_str+'phase_stability'+Photo
    Figure_Name = Parameters_str
    Atom_Center = Initial_Settings.AtomCenter_Pos()
    Cut_Width = Initial_Settings.CutWidths()

    #Calculating
    Photo_Ind = Ini_Photo
    while(Photo_Ind <= Fin_Photo):
        plt.close('all')
        Load_Name = Folder_Name+PhotoName_Pre+'%03d'%Photo_Ind+PhotoName_End
        Save_Name = Folder_Name+PhotoName_Pre+'%03d'%Photo_Ind+'od'
        Data_ThisPic_AtomNum, Data_ThisPic_AtomRegion, ni = \
        bf.Load_Pic_And_Cal(Photo_Ind, Load_Name, File_Mode, Save_Name, \
        SaveFigure_Address, Atom_Center, Cut_Width, 5, 1)
        small = 0
        big = 0
        for i in range(0, 4, 1):
            small += Data_ThisPic_AtomNum[i]
        big = Data_ThisPic_AtomNum[4]
#        ratio = (small)/(small+big)
        ratio = (small-0.007907518811609535)/(small-0.007907518811609535+big)
        Ratio_Mat[Row_Num, Photo_Ind-Ini_Photo] = ratio
        smalls[Row_Num, Photo_Ind-Ini_Photo] = small
        

        Photo_Ind += 1
    Ratio_Mean = np.mean(Ratio_Mat[Row_Num, :])
    np.savez(Save_Address+r'Ratio_Mat'+'.npz', Ratio_Mat=Ratio_Mat[Row_Num, :])
#    sio.savemat(Save_Address+r'Ratio_Mat'+'.mat', {'Ratio_Mat': Ratio_Mat[Row_Num, :]})
    sio.savemat(Save_Address+r'Ratio_Mat_nobg'+'.mat', {'Ratio_Mat_nobg': Ratio_Mat[Row_Num, :]})
    #plot
    Range = np.max(Ratio_Mat[Row_Num, :])-np.min(Ratio_Mat[Row_Num, :])
    fig = plt.figure(Row_Num)
    plt.plot(Ratio_Mat[Row_Num, :],'-*')
    plt.text(3, 0.21, 'Range=%.2f'%(Range))
    fig.savefig(SaveFigure_Address+r'Ratio'+'.png')
    fig.savefig(SaveFigure_Address+r'Ratio'+'.pdf')
#    plt.pause(0.5)
#    plt.close()

#%%
# SpinPol_Mean = np.mean(Ratio_Mat, 0)
# SpinPol_Std = np.std(Ratio_Mat, 0)

#%%Plot data with errorbar
# fig = plt.figure(100)
# plt.errorbar(Time, SpinPol_Mean, yerr=SpinPol_Std, fmt='o', \
# ecolor=[0, 0, 1], markerfacecolor=[0, 0.6, 1], markeredgecolor=[0, 0, 1], \
# markersize=24, elinewidth=3, markeredgewidth=3, capsize=5)

# #%Fit data with cosin function
# Par = MSJJ_Fit.fit(Time, SpinPol_Mean, SpinPol_Std)
# Time_Fit = np.linspace(Time[0], Time[-1], 200)
# SpinPol_Fit = MSJJ_Fit.f(Time_Fit, Par[0], Par[1], Par[2])
# plt.plot(Time_Fit, SpinPol_Fit, color=[1, 0, 0], linewidth=4)

#%%


#%%
time_end=time.time()
print('Time spent: ', time_end-time_start, 's')


        
        
        




    

